package com.badlogic.androidgames.mypirates.Sprite;

import com.badlogic.androidgames.framework.Game;
import com.badlogic.androidgames.framework.Graphics;
import com.badlogic.androidgames.framework.Graphics.PixmapFormat;
import com.badlogic.androidgames.mypirates.Constants;
import com.badlogic.androidgames.mypirates.MyPirateGame;

import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.Rect;

import java.util.ArrayList;

public class MySprite {
	protected MyPirateGame currentGame;
	
	Bitmap Texture;
	
	protected ArrayList<Rect> frames = new ArrayList<Rect>();
	
	protected int frameWidth = 0;
    protected int frameHeight = 0;
    
    protected int currentFrame = 0;
    
    public int x;
    public int y;
    
    public float frameTime = 0.08f;
    protected float timeForCurrentFrame = 0.0f;
    
    public boolean destroyed = false;
    
    public Point Size;
    
    public Rect destination()
    {
		return new Rect(
				Constants.InitialPositionX + Constants.MapPieceWidth * x,
				Constants.InitialPositionY + Constants.MapPieceWidth * y,
				Constants.InitialPositionX + Constants.MapPieceWidth * x + Constants.MapPieceWidth,
				Constants.InitialPositionY + Constants.MapPieceWidth * y + Constants.MapPieceHeight);
    }
    
    public Rect source(){
    	if(frames.size() == 0)
    		return null;
    	return frames.get(currentFrame);
    }
    
    public MySprite(Game game){
    	currentGame = (MyPirateGame)game;
    }
    
    protected void Initialize (String textureName, Rect initialFrame, Point size, Point position){
    	Graphics g = currentGame.getGraphics();
    	Texture = g.newPixmap(textureName, PixmapFormat.ARGB8888);
    	frameWidth = initialFrame.width();
    	frameHeight = initialFrame.height();
    	this.Size = size;
    	x = position.x;
    	y = position.y;
    	InitialFrames(initialFrame, size);
    }
    
    private void InitialFrames(Rect initialFrame, Point size){
    	if(size.x == 1){
    		for(int i = 0 ; i < size.y ;i++){
    			frames.add(new Rect(initialFrame.left, initialFrame.top + initialFrame.height() * i, initialFrame.left +  initialFrame.width(), initialFrame.top + initialFrame.height() * (i + 1)));
    		}
    	}
    	else if(size.y == 1){
    		for(int i = 0 ; i < size.x ;i++){
    			frames.add(new Rect(initialFrame.left + initialFrame.width() * i, initialFrame.top, initialFrame.left + initialFrame.width() * (i + 1), initialFrame.top + initialFrame.height()));
    		}
    	}
    }
    
    public void Update (float gameTime){
    	currentFrame = (currentFrame + 1) % frames.size();
    }
    
    public void Draw(Graphics g){
    	Rect src = source();
    	Rect dest = destination();
    	if(src != null){
    		g.drawBitmap(Texture, src, dest);
    	}
    }
}
